import axios from 'axios'

const homeShopModule = {
  state: {
    shopList: [],
    newList: [], // 用来做数组排序 (无配送费)
    newList1: [], // 用来做数组排序 (有配送费)
  },
  actions: {
    // 请求店铺数据
    getShop (context) {
      axios({ url: '/shopList.json' })
        .then(data => {
          context.commit('showShop', data.data)
        })
    },
  },
  mutations: {
    // 展示店铺
    showShop (state, value) {
      state.shopList = value
    },
    handleSortShop (state, value) {
      switch (value) {
        case 1: // 速度最快
          state.shopList.sort((a, b) => (a.deliveryTimeTip.slice(0, 2)) - (b.deliveryTimeTip.slice(0, 2)))
          break
        case 2: // 评分最高
          state.shopList.sort((a, b) => b.wmPoiScore - a.wmPoiScore)
          break
        case 3: // 起送价最低
          state.shopList.sort((a, b) => a.minPriceTip.slice(4, 6) - b.minPriceTip.slice(4, 6))
          break
        case 4: // 配送费最低
          state.shopList.forEach(item => {
            // 先判断是否有配送费
            if (!item.origin_shipping_fee_tip) {
              state.newList.push(item) // 无配送费的
            }
          })
          state.newList1 = state.shopList.filter(item => item.origin_shipping_fee_tip) // 有配送费
          state.newList1.sort((a, b) => a.origin_shipping_fee_tip.slice(1) - b.origin_shipping_fee_tip.slice(1))
          state.shopList = [...state.newList1, ...state.newList] // 合并
          break
        case 5: // 人均高到低
          state.shopList.sort((a, b) => b.averagePriceTip.slice(4, 6) - a.averagePriceTip.slice(4, 6))
          break
      }
    },
    handleSortSale (state) {
      state.shopList.sort((a, b) => b.monthSalesTip.slice(3) - a.monthSalesTip.slice(3))
    },
    handleSortDistance (state) {
      state.shopList.map(item => {
        if (item.distance.includes('k')) { // km级
          state.newList.push(item)
        } else {
          state.newList1.push(item) // m级
        }
      })
      state.newList.sort((a, b) => a.distance.slice(0, 3) - b.distance.slice(0, 3))
      state.newList1.sort((a, b) => a.distance.slice(0, 3) - b.distance.slice(0, 3))
      state.shopList = [...state.newList1, ...state.newList]
    },
  },
}

export default homeShopModule
